//
//  ViewController.m
//  toutiao
//
//  Created by duyujin1 on 2021/7/21.
//

#import "DUNewsViewController.h"
#import "DUNormalTableViewCell.h"
#import "DUMediator.h"
#import "DUDeleteCellView.h"
#import "DUListLoader.h"
#import "DUListItem.h"
#import "DUSearchView.h"
#import "define.h"
#import <Masonry.h>
#import "DUDetailViewController.h"

@interface DUNewsViewController ()<UITableViewDelegate,UITableViewDataSource,DUNormalTableViewCellDelete>
@property(nonatomic,strong,readwrite)UITableView * tableView;
@property(nonatomic,strong,readwrite)NSArray * dataArray;
@property(nonatomic,strong,readwrite)DUListLoader * listLoader;
@property(nonatomic,strong,readwrite)DUSearchView * search;
@property(nonatomic,strong,readwrite)UIRefreshControl * refreshControl;
@property(nonatomic,strong,readwrite)UIScrollView * scrollView;

@end

@implementation DUNewsViewController

-(instancetype)init{
    if(self=[super init]){
        NSString * title=NSLocalizedString(@"news", nil);
        self.tabBarItem.title=title;
        self.tabBarItem.image=[UIImage imageNamed:@"icon.bundle/page@2x.png"];
        self.tabBarItem.selectedImage=[UIImage imageNamed:@"icon.bundle/page_selected@2x.png"];
        self.navigationItem.title=title;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.refreshControl];
    //[self search];
    self.listLoader=[[DUListLoader alloc] init];
    
    __weak typeof(self) wself=self;
    [self.listLoader loadListDataWithFinishBlock:^(BOOL success, NSArray<DUListItem *> * _Nonnull dataArray) {
        __strong typeof(wself) strongSelf=wself;
        strongSelf.dataArray=dataArray;
        [strongSelf.tableView reloadData];
    } isRefresh:NO];
    
}

#pragma mark ---tableViewDdelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.search.hidden=YES;
    DUListItem * item=[self.dataArray objectAtIndex:indexPath.row];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
//    __kindof UIViewController * detailController=[DUMediator detailViewControllerWithUrl:item.articleUrl];
//    detailController.title=[NSString stringWithFormat:@"%@",@(indexPath.row)];
//    detailController.view.backgroundColor=[UIColor whiteColor];
    
    //[DUMediator openUrl:@"detail://" pramas:@{@"url":item.articleUrl,@"controller":self.navigationController}];
    //key-value存储已读
    
    Class cls=[DUMediator classForPortocol:@protocol(DUDetailViewControllerProtocol)];
    [self.navigationController pushViewController:[[cls alloc] detailViewControllerWithUrl:item.url] animated:YES];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:item.sourceId];
    //[self.navigationController pushViewController:detailController animated:YES];
}

#pragma mark ---dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (DUNormalTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DUNormalTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:@"id"];
    if(!cell){
       cell=[[DUNormalTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"id"];
        cell.delegate=self;
    }
    
    [cell layoutTableViewCellWithItem:[self.dataArray objectAtIndex:indexPath.row]];
    return cell;
}

- (void)tableViewCell:(UITableView *)tableViewCell clickDeleteButton:(UIButton *)deleteButton{
    DUDeleteCellView *deleteView = [[DUDeleteCellView alloc] initWithFrame:self.view.bounds];
    CGRect rect = [tableViewCell convertRect:deleteButton.frame toView:nil];

    __weak typeof(self)wself = self;
    [deleteView showDeleteViewFromPoint:rect.origin clickBlock:^{
         __strong typeof(wself) strongSelf = wself;
        NSIndexPath *delIndexPath = [strongSelf.tableView indexPathForCell:tableViewCell];
        if (strongSelf.dataArray.count > delIndexPath.row) {
            //删除数据
            NSMutableArray *dataArrayTmp = [strongSelf.dataArray mutableCopy];
            [dataArrayTmp removeObjectAtIndex:delIndexPath.row];
            strongSelf.dataArray = [dataArrayTmp copy];
            //删除cell
            [strongSelf.tableView deleteRowsAtIndexPaths:@[delIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
     }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if(self.refreshControl.refreshing){
        [self refreshNews];
    }
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView=[[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    return _tableView;
}

-(DUSearchView *)search{
    if(!_search){
        _search=[[DUSearchView alloc] initWithFrame:CGRectZero];
        [self.navigationController.navigationBar addSubview:_search];
        [_search mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(self.navigationController.navigationBar).offset(10);
            make.bottom.right.mas_equalTo(self.navigationController.navigationBar).offset(-10);
        }];
    }
    return _search;
}

-(UIRefreshControl *)refreshControl{
    if(!_refreshControl){
        _refreshControl=[[UIRefreshControl alloc] init];
        _refreshControl.tintColor=UIColor.orangeColor;
    }
    return _refreshControl;
}

-(void)refreshNews{
    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self.refreshControl endRefreshing];
        [timer invalidate];
        timer=nil;
        __weak typeof(self) wself=self;
        [self.listLoader loadListDataWithFinishBlock:^(BOOL success, NSArray<DUListItem *> * _Nonnull dataArray) {
            __strong typeof(wself) strongSelf=wself;
            strongSelf.dataArray=dataArray;
            [strongSelf.tableView reloadData];
        } isRefresh:YES];
    }];
}

@end
